package com.yongyun.reptile.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 
* @author liyongkang
* @version 创建时间：2018年4月26日 下午4:50:11 
* 类说明 ：HttpClient工具类
*/

public class HttpClientUtils {
	
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	
	private static final String CHARSET = "UTF-8";
	
	/**
	 * post方法
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return 请求结果
	 * @throws Exception 
	 */
	public static String post(String url, Map<String, String> paramsMap) throws Exception{
		String resultString = "";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		try {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			for(String key:paramsMap.keySet()){
				params.add(new BasicNameValuePair(key, paramsMap.get(key)));
			}
			try {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET);
				httpPost.setEntity(entity);
				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity resultEntity = response.getEntity();
				if(resultEntity != null){
					resultString = EntityUtils.toString(resultEntity, CHARSET);
				}
			} catch (UnsupportedEncodingException e) {
				logger.error("HttpClient请求失败", e);
				throw new Exception("HttpClient请求失败");
			}
		} finally {
			httpPost.releaseConnection();
		}
		return resultString;
	}
	
	public static String get(String url, Map<String, String> param){
		 // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
	}
	
}
